﻿/*
VALIDATIONGROUPS 1.0
--------------------
Emula ValidationGroups de ASP.NET utilizando el plugin en jquery.validate.js
Como Funciona:
- El formulario a validar debe estar dentro de un div con class="validationGroup"
- El boton que causa la validacion debe tener class="causesValidation"
- El boton que causa la validacion debe estar dentro de un div con class="buttonPnl"
- Para no validar algun campo, este debe tener class="ignoreValidation"
- Escribir 'rules' y 'messages' de plugin jquery.validate en el archivo aspx
- En la funcion validate del plugin poner 'onsubmit: false' para que este script maneje la validacion
- Requiere el plugin jquery scrollTo
- Si se desea tener algun argumento a la hora de hacer postBack, es necesario que se cree un anchor que tenga
    class="clickMeBeforePostBack" y ahi se guarden los eventArgs en el hiddenField con class="hdnValidationEventArgs" 
    de donde se pediran luego; todo esto debe estar dentro del panel con class="validationGroup"

CREADO POR:
Dave Ward: http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/
ADAPTACION:
Hugo Giusti & the power of grayskull
READAPTACION:
Jose Miguel Alvarez
*/

$(document).ready(function () {
    // Search for controls marked with the causesValidation flag 
    //  that are contained anywhere within elements marked as 
    //  validationGroups, and wire their click event up.
    $('.validationGroup .causesValidation').click(ValidateAndSubmit);
    
    //If a hiddenFunction exist, the next causesValidation must not be keypress able.
    if ($('.hiddenFunction').length > 0) {
        $('.hiddenFunction').prev('.causesValidation').keydown(function (evt) {
            evt.preventDefault();
            return false;
        });
    }
    // Select any input[type=text] elements within a validation group
    //  and attach keyup handlers to all of them.
    $('.validationGroup').find('input').not(':submit, :reset, :hidden').each(function () {
        $(this).keydown(function (evt) {
            // Only execute validation if the key pressed was enter.
            if (evt.keyCode == 13) {
                // We want to prevent the default form action regardless.
                evt.preventDefault();
                // Find the button panel to click the submit button
                var buttonPanel = $(this).closest('.validationGroup').find('.buttonPnl');
                //submit button is the one with "causesValidation" class
                buttonPanel.children('.causesValidation').click();
                return false;
            }
        });
    });
    $('.validationGroup').find('select').each(function () {
        $(this).keydown(function (evt) {
            // Only execute validation if the key pressed was enter.
            if (evt.keyCode == 13) {
                // We want to prevent the default form action regardless.
                evt.preventDefault();
                // Find the button panel to click the submit button
                var buttonPanel = $(this).closest('.validationGroup').find('.buttonPnl');
                //submit button is the one with "causesValidation" class
                buttonPanel.children('.causesValidation').click();
                return false;
            }
        });
    });
});

function ValidateAndSubmit(evt) {
    // Ascend from the button that triggered this click event 
    //  until we find a container element flagged with 
    //  .validationGroup and store a reference to that element.
    var $group = $(evt.currentTarget).closest('.validationGroup');
 
    var isValid = true;
 
    // Descending from that .validationGroup element, find any input
    //  elements within it, iterate over them, and run validation on 
    //  each of them.
    $group.find(':input:not(.ignoreValidation)').each(function (i, item) {
        if (!$(item).valid()) {
            isValid = false;
        }
    });
    //This is used to scroll to the first error label.
    if ($(evt.currentTarget).parent().closest('.validationGroup').find('.error:visible:first').length) {
        $.scrollTo($(evt.currentTarget).parent().closest('.validationGroup').find('.error:visible:first'), { duration: 1000 });
        $(evt.currentTarget).parent().closest('.validationGroup').find('.error:visible:first').next().focus();
    }
    // If any fields failed validation, prevent the button's click 
    //  event from triggering form submission.
    if (!isValid)
    {
        evt.preventDefault();
    } 
    else if (evt.button != 0)// The event comes from Enter keypress, do postback manually
    {
        // first we need to extract event Target from evt.currentTarget.href 
        //  (the first parameter for __doPostback)
        // this is a masterpage safe method, also works without masterpage

        var target = evt.currentTarget.href;
        //it has to be a call from a asp.net control
        if (target.match("^javascript:")) { 
            var hasOptions = target.match("Options");
            var quotes = "'";

            if (hasOptions) { quotes = '"'; }

            var quotesIndex = target.indexOf(quotes) + 1;
            target = target.substring(quotesIndex);
            quotesIndex = target.indexOf(quotes);
            target = target.substring(0, quotesIndex);


            //If it needs any eventArgument, the way to do it is this:
            //It needs a hidden anchor (.clickMeBeforePostBack) that has a click method where the eventArgs
            //need to be asigned to the .hdnValidationEventArgs  hiddenField to get it here.
            var eventArgs = '';
            if ($(evt.currentTarget).closest('.validationGroup').find('.clickMeBeforePostBack').length > 0) {
               $(evt.currentTarget).closest('.validationGroup').find('.clickMeBeforePostBack').click();
                eventArgs = $(evt.currentTarget).closest('.validationGroup').find('.hdnValidationEventArgs').val();
            }
            __doPostBack(target, eventArgs);

        }

    }
    //if a hiddenFunction exist after the normal postback, it is clicked and prevent the normal postback
    if ($(evt.currentTarget).parent().children('.hiddenFunction').length && isValid) {
        $(evt.currentTarget).parent().children('.hiddenFunction').click();
        evt.preventDefault();
    }
}